﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Terminal;
using com.nm.library.Helper;
using NHibernateVertica;
using Senparc.Weixin.Helpers.Extensions;
using Senparc.Weixin.Work.AdvancedAPIs;
using Senparc.Weixin.Work.AdvancedAPIs.MailList;
using Senparc.Weixin.Work.Containers;
using Senparc.Weixin.Work.Helpers;
using WeiXinAPI.Common;
using WeiXinAPI.model;

namespace WeiXinAPI
{
    public class WxUserHandler : BaseHandler
    {
        public VerticaDataHelper Helper { get; set; } = new VerticaDataHelper();

        #region 获取部门成员列表(Jstree树结构) GetDepartmentList

        [MustLogin]
        [Description("获取部门成员列表(Jstree树结构)")]
        [ReturnType(typeof(IList<DepartmentListForJsTree>))]
        public ApiResult GetDepartmentList(string wxConfig)
        {
            var wxInfo = WXBaseHandler.TryGetWxCorpInfo(wxConfig);
            if (wxInfo.CorpInfo == null)
            {
                return Error(wxInfo.Message);
            }

            //这里要用ContactsSecret
            var accessToken =
                AccessTokenContainer.TryGetToken(wxInfo.CorpInfo.CorpID, wxInfo.CorpInfo.CommunicationSercet);

            //按需求要将部门跟用户合并到一个jsTree里面，可是Department的id跟UserList_Simple的id类型不一样,没法放在原本的DepartmentList里面，所以新建Tree实体
            var departmentTree = new List<DepartmentListForJsTree>();
            //获取所有部门
            var departmentList = MailListApi.GetDepartmentList(accessToken).department;
            var n = 0;
            //转换部门到tree
            foreach (var department in departmentList)
            {
                //n++;
                departmentTree.Add(new DepartmentListForJsTree()
                {
                    id = department.id,
                    name = department.name,
                    order = department.order,
                    parentid = department.parentid,
                    UserId = "",
                    DepartmentId = department.id
                });
            }

            //获取全部的成员
            var memberList = MailListApi.GetDepartmentMember(accessToken, 1, 1).userlist;
            //加入成员到tree
            foreach (var member in memberList)
            {
                foreach (var d in member.department)
                {
                    n++;
                    departmentTree.Add(new DepartmentListForJsTree()
                    {
                        id = Guid.NewGuid().GetHashCode(),
                        name = member.name,
                        order = 0,
                        parentid = d,
                        UserId = member.userid
                    });
                }
            }

            return Success(departmentTree);
        }

        #endregion

        #region 设置用户与报表的关联关系 SetMemberReportRelation

        [JsonType]
        [MustLogin]
        [Description("设置用户与报表的关联关系")]
        [ReturnType(typeof(int))]
        public ApiResult SetMemberReportRelation(MemberDepartmentInfo infos)
        {
            var wxInfo = WXBaseHandler.TryGetWxCorpInfo(infos.WxConfig);
            if (wxInfo.CorpInfo == null)
            {
                return Error(wxInfo.Message);
            }


            var dc = new TerminalEntities();
            var list = new List<MemberReport>();

            var userIds = infos.MemberIdList.Select(t => t.userId);


            //先删掉选中的用户的所有设置
            dc.MemberReport.RemoveRange(dc.MemberReport.Where(x => x.CIdentification == wxInfo.CorpInfo.CIdentification && userIds.Contains(x.UserId)));
            dc.SaveChanges();

            //按用户依次设置选择的版本Id
            foreach (var memberId in infos.MemberIdList)
            {
                foreach (var reportId in infos.ReportIdList)
                {
                    var model = new MemberReport
                    {
                        CIdentification = wxInfo.CorpInfo.CIdentification,
                        UserId = memberId.userId,
                        UserName = memberId.userName,
                        ReportId = reportId
                    };
                    list.Add(model);
                }
            }

            if (list.Count > 0)
            {
                dc.MemberReport.AddRange(list);
                var n = dc.SaveChanges();
                return Success(n > 0);
            }
            return Success(0);
        }

        #endregion
    }





    public class jssdkConfig
    {
        public long timeStamp { get; set; }
        public string nonceStr { get; set; }
        public string signature { get; set; }
        public string ticket { get; set; }
        public string corpId { get; set; }
    }
}
